﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HKEA.CMS.Core.Utility;
using HKEA.CMS.Core.BLL;
using HKEA.CMS.Core.Models;
using System.Data;
using System.Transactions;
using HKEA.CMS.Core.BLL.Tbl;
using HKEA.CMS.Core.BLL.Mtbl;
namespace WebApplication
{
    public partial class Brand : BasePage
    {
        #region
        static mtblBrand entBrandLog = new mtblBrand();
        static int MedioBrand;
        #endregion

        protected int customeruid = 0;
        protected int branduid = 0;
        protected string type = "";
        tblCustomer customerENT = new tblCustomer();
        tblCustomerBLL customerBLL = new tblCustomerBLL();
        mtblBrandBLL brandBLL = new mtblBrandBLL();
        
        tblBrand_ProdCat brand_prodCatENT = new tblBrand_ProdCat();
        tblBrand_ProdCatBLL brand_prodCatBLL = new tblBrand_ProdCatBLL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Request.QueryString[Constant.UrlParamName.CustomerUID] != null)
                {
                    if (int.TryParse(Request.QueryString[Constant.UrlParamName.CustomerUID], out customeruid))
                    {
                        InitPage();
                        BindStaticEnt();
                    }
                    else
                    {
                        SetNoOption();
                        lblMeg.Text = ResourceManage.GetResourceString("msg200001");
                    }
                }
                else
                {
                    SetNoOption();
                    lblMeg.Text = ResourceManage.GetResourceString("msg200002");
                }
            }
        }
        #region 页面加载
        private void InitPage()
        {
            customerENT.CustomerUID = customeruid;
            customerENT = customerBLL.GetEntity(customerENT);
            if (customerENT != null)
            {
                type = Request.QueryString["type"];
                BindProductCat();
                BindBrandList();
                BindBrandImg(customerENT.CustomerUID);
                hidCustomerUID.Value = customerENT.CustomerUID.ToString();
                if (Request.QueryString[Constant.UrlParamName.BrandUID] != null)
                {
                    lkQuit.NavigateUrl = lkAdd.NavigateUrl = "Brand.aspx?" + Constant.UrlParamName.CustomerUID + "=" + customeruid + "&type=add";
                    if (int.TryParse(Request.QueryString[Constant.UrlParamName.BrandUID], out branduid))
                    {
                        mtblBrand brandENT = new mtblBrand();
                        brandENT.BrandUID = branduid;
                        brandENT.CustomerUID = customerENT.CustomerUID;
                        brandENT = brandBLL.GetEntity(brandENT);
                        if (brandENT != null)
                        {
                            hidBrandUID.Value = brandENT.BrandUID.ToString();
                            BingImgRelated();
                            SetBrandValue(brandENT);
                            //查询Brand相关ProductCat
                            SetBrandToProductCat(brandENT);
                        }
                        else
                        {
                            SetNoOption();
                            lblMeg.Text = ResourceManage.GetResourceString("msg200014");
                        }
                    }
                }
            }
            else
            {
                SetNoOption();
                lblMeg.Text = ResourceManage.GetResourceString("msg200014");
            }
        }
        private void SetNoOption()
        {
            lkBtnSave.Enabled = false;
            hidAllowOption.Value = "false";
        }

        private void SetBrandValue(mtblBrand ent)
        {
            //文本赋值
            txtBrandIntro_Chi.Text = ent.Intro_Chi;
            txtBrandIntro_Eng.Text = ent.Intro_Eng;
            txtBrandName_Chi.Text = ent.BrandName_Chi;
            txtBrandName_Eng.Text = ent.BrandName_Eng;            
        }
        //查询Brand相关ProductCat  productSubCat赋值给
        private void SetBrandToProductCat(mtblBrand ent)
        {
            brand_prodCatENT.BrandUID = ent.BrandUID;
            brand_prodCatENT.Deleted = 0;
            var list = brand_prodCatBLL.GetListByENT(brand_prodCatENT);
            string str = string.Empty;
            if (list.Count > 0)
            {
                list= list.OrderBy(a=>a.BrandUID).ToList();
                foreach (var temp in list)
                {
                    str += temp.ProductCatUID + ",";
                }
            }
            hidRelatedBrandProdCatStrUID.Value = str;
        }
        //绑定Customer所有图片列表
        protected void BindBrandImg(int customeruid)
        {
            tblMediaRoom mediaroomENT = new tblMediaRoom();
            tblMediaRoomBLL mediaroomBLL = new tblMediaRoomBLL();
            mediaroomENT.CustomerUID = customeruid;
            mediaroomENT.IsPublish = 1;
            mediaroomENT.MediaType = Constant.MediaType.image;
            mediaroomENT.Category = Constant.MediaRoomCategory.brand_logo;
            var list = mediaroomBLL.GetListByENT(mediaroomENT);
            rptImgList.DataSource = list;
            rptImgList.DataBind();
        }
        //绑定Brand Logo （只一个图片）
        protected void BingImgRelated()
        {
            mtblBrand ent = new mtblBrand();
            ent.BrandUID = branduid;
            ent.CustomerUID = customerENT.CustomerUID;
            ent = brandBLL.GetEntity(ent);
            if (ent != null)
            {
                tblMediaRoom roomENT = new tblMediaRoom();
                tblMediaRoomBLL roomBLL = new tblMediaRoomBLL();
                if (ent.BrandLogo > 0)
                {
                    roomENT = roomBLL.GetEntity((int)ent.BrandLogo);
                    List<tblMediaRoom> roomlist = new List<tblMediaRoom>();
                    if (roomENT != null)
                    {
                        roomlist.Add(roomENT);
                        hidMediaRoomUID.Value = roomENT.MediaRoomUID.ToString();
                    }
                    rptRelatedImgList.DataSource = roomlist;
                    rptRelatedImgList.DataBind();
                }
            }
        }
        //绑定ProductCat列表
        private void BindProductCat()
        {
            List<string> strlist = new List<string>();
            strlist.Add("A");
            strlist.Add("B");
            strlist.Add("C");
            strlist.Add("D");
            strlist.Add("E");
            DataTable dt = new DataTable();
            DataColumn col = new DataColumn();
            col.ColumnName = "startwith";
            dt.Columns.Add(col);
            foreach (var temp in strlist)
            {
                DataRow dr = dt.NewRow();
                dr[0] = temp;
                dt.Rows.Add(dr);
            }
            rptStart.DataSource = dt;
            rptStart.DataBind();
        }
        //绑定CustomerBrand列表
        private void BindBrandList()
        {
            mtblBrand ent = new mtblBrand();
            ent.CustomerUID = customeruid;
            ent.Deleted = 0;
            var list = brandBLL.GetListDetailByENT(ent);
            rptBrandList.DataSource = list;
            rptBrandList.DataBind();
            //add by martin  ,实行 js  AverageBrand（）函数 
            ScriptManager.RegisterStartupScript(this, this.GetType(), "myscript", "AverageBrand();", true);
        }

        private void BindStaticEnt() {
            entBrandLog = GetBrandValue(entBrandLog);
        }
        private string CheckChange() {
            string str=string.Empty;
            int tempMedioBrand = hidMediaRoomUID.Value.Equals("") ? 0 : Convert.ToInt32(hidMediaRoomUID.Value);
            mtblBrand ent = new mtblBrand();
            ent = GetBrandValue(ent);
            if (entBrandLog.BrandName_Chi != ent.BrandName_Chi) 
                str += "品牌名稱 change to " + ent.BrandName_Chi;
            if (entBrandLog.BrandName_Eng != ent.BrandName_Eng)
                str += "Brand Name change to "+ent.BrandName_Eng;
            if (entBrandLog.Intro_Chi != ent.Intro_Chi)
                str += "品牌簡介 changge to "+ent.Intro_Chi;
            if (entBrandLog.Intro_Eng != ent.Intro_Eng)
                str += "Brand Description change to "+ent.Intro_Eng;
            if (Convert.ToInt32(ent.BrandLogo) != tempMedioBrand) 
                str += "Brand image have change";
            return str;
        }
        #endregion

        protected void rptStart_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            string ProductCatID = (string)((DataRowView)e.Item.DataItem)["startwith"];
            Repeater rptCat = e.Item.FindControl("rptCat") as Repeater;
            Repeater rptCatForSubCat = e.Item.FindControl("rptCatForSubCat") as Repeater;
            if (rptCat != null)
            {

                mtblProductCat catENT = new mtblProductCat();
                mtblProductCatBLL catBLL = new mtblProductCatBLL();
                catENT.ProductCatID = ProductCatID;
                catENT.Deleted = 0;
                var list = catBLL.GetListByENT(catENT);
                rptCat.DataSource = list;
                rptCat.DataBind();
                rptCatForSubCat.DataSource = list;
                rptCatForSubCat.DataBind();
            }
        }

        protected void rptCatForSubCat_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                Repeater rptSubCat = e.Item.FindControl("rptSubCat") as Repeater;
                if (rptSubCat != null)
                {
                    mtblProductCat catENT = new mtblProductCat();
                    catENT = e.Item.DataItem as mtblProductCat;
                    mtblProductSubCat subCatENT = new mtblProductSubCat();
                    mtblProductSubCatBLL subCatBLL = new mtblProductSubCatBLL();
                    subCatENT.ProductCatUID = catENT.ProductCatUID;
                    subCatENT.Deleted = 0;
                    var list = subCatBLL.GetListByENT(subCatENT);
                    rptSubCat.DataSource = list;
                    rptSubCat.DataBind();
                }
            }
        }

        #region 按钮事件
        protected void lkBtnSave_Click(object sender, EventArgs e)
        {
            int.TryParse(Request.QueryString[Constant.UrlParamName.CustomerUID] , out customeruid);
            int.TryParse(Request.QueryString[Constant.UrlParamName.BrandUID], out branduid);
            bool IsSuccess = false;
            if (customeruid > 0)
            {
                if (branduid > 0)
                {
                    mtblBrand brandENT = new mtblBrand();
                    brandENT.CustomerUID = customeruid;
                    brandENT.BrandUID = branduid;
                    var temp = brandBLL.GetEntity(brandENT);
                    if (temp != null)
                    {
                        IsSuccess = UpdateMethod();
                    }
                    else
                    {
                        IsSuccess = AddMethod();
                    }
                }
                else
                {
                    IsSuccess = AddMethod();
                }
                if (IsSuccess)
                {
                    BingImgRelated();
                    BindBrandList();
                }
            }
        }

        //Customer上传图片，刷新图片列表触发事件
        protected void btnRefreshImgList_Click(object sender, EventArgs e)
        {
            if (int.TryParse(Request.QueryString[Constant.UrlParamName.CustomerUID], out customeruid))
            {
                BindBrandImg(customeruid);
            } 
        }
        //刷新BrandList列表触发事件
        protected void btnRefreshBrandList_Click(object sender, EventArgs e)
        {
            if (int.TryParse(Request.QueryString[Constant.UrlParamName.CustomerUID], out customeruid))
            { 
                BindBrandList();
            }
        }

        private bool UpdateMethod()
        {
            bool IsSuccess = true;
            mtblBrand brandENT = new mtblBrand();
            brandENT.BrandUID = branduid;
            brandENT.CustomerUID = customeruid;
            brandENT = brandBLL.GetEntity(brandENT);
            if (brandENT != null)
            {
                brandENT = GetBrandValue(brandENT);
                List<int> ToAddSubCatUIDList = new List<int>();
                List<int> ToDelSubCatUIDList = new List<int>();
                ToAddSubCatUIDList = GetNeedToAdd();
                ToDelSubCatUIDList = GetNeedToDel();
                TransactionOptions options = new TransactionOptions();
                options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
                options.Timeout = new TimeSpan(0, 5, 0);
                string lastModifyBy = Common.GetManageName();

                using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
                {
                    brandBLL.UpdateENT(brandENT);
                    brand_prodCatBLL.SaveList(ToAddSubCatUIDList, ToDelSubCatUIDList, branduid, lastModifyBy);
                    WriteToLog(ToAddSubCatUIDList,ToDelSubCatUIDList);//写入Log
                    try { scope.Complete(); }
                    catch (Exception er)
                    {
                        IsSuccess = false;
                    }
                }
                SetBrandToProductCat(brandENT);
            }
            else
            {
                lblMeg.Text = ResourceManage.GetResourceString("msg200014");
            }
            if (IsSuccess)
            { lblMeg.Text = ResourceManage.GetResourceString("msg200004"); }
            else
            { lblMeg.Text = ResourceManage.GetResourceString("msg200003"); }
            return IsSuccess;
        }
        private bool AddMethod()
        {
            bool IsSuccess = true;
            mtblBrand brandENT = new mtblBrand();
            brandENT=GetBrandValue(brandENT);
            List<int> ToAddSubCatUIDList = new List<int>();
            List<int> ToDelSubCatUIDList = new List<int>();
            ToAddSubCatUIDList = GetNeedToAdd();
            ToDelSubCatUIDList = GetNeedToDel();
            TransactionOptions options = new TransactionOptions();
            options.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
            options.Timeout = new TimeSpan(0, 5, 0);
            string lastModifyBy=Common.GetManageName();
            using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, options))
            {
                brandENT= brandBLL.InsertENTReturnENT(brandENT);
                if (brandENT != null)
                {
                    branduid = brandENT.BrandUID;
                    brand_prodCatBLL.SaveList(ToAddSubCatUIDList, ToDelSubCatUIDList, branduid, lastModifyBy);
                    WriteToLog(ToAddSubCatUIDList, ToDelSubCatUIDList);//写入Log
                }
                try { scope.Complete(); }
                catch (Exception er) {
                    IsSuccess = false;
                }
            }
            if (IsSuccess)
            { lblMeg.Text = ResourceManage.GetResourceString("msg200006");
            ScriptManager.RegisterStartupScript(this, this.GetType(), "cleartxt", "ClearText();", true);
            }
            else
            { lblMeg.Text = ResourceManage.GetResourceString("msg200005"); }
            return IsSuccess;
        }

        #endregion

        #region  获值
        private mtblBrand GetBrandValue(mtblBrand ent)
        {
            ent.CustomerUID = customeruid;
            ent.BrandName_Chi = txtBrandName_Chi.Text;
            ent.BrandName_Eng = txtBrandName_Eng.Text;
            ent.Intro_Chi = txtBrandIntro_Chi.Text;
            ent.Intro_Eng = txtBrandIntro_Eng.Text;
            ent.LastModifyBy = Common.GetManageName();
            ent.LastModifyDate = DateTime.Now;
            ent.CreationDate = DateTime.Now;
            int logouid = 0;
            int.TryParse(hidMediaRoomUID.Value,out logouid);
            ent.BrandLogo = logouid;
            return ent;
        }

        private List<int> GetNeedToDel()
        {
            return GetListFromHid(hidRelatedNeedToDelete);
        }
        private List<int> GetNeedToAdd()
        {
            return GetListFromHid(hidRelatedNeedToAdd);
        }

        private List<int> GetListFromHid(HiddenField hidName)
        {
            var list = new List<int>();
            if (!string.IsNullOrEmpty(hidName.Value))
            {
                list = (hidName.Value).StringToList();
            }
            return list;
        }

        #endregion

        #region
        protected void WriteToLog(List<int> add,List<int> delete) {
            string info = string.Empty;
            mtblProductSubCat entProSubCat = new mtblProductSubCat();

            List<mtblProductSubCat> list = mtblProductSubCatBLL.GetInstance().GetListByENT(entProSubCat);
            for (int i = 0; i < add.Count - 1; i++)
            {
                var result = list.Where(a => a.ProductCatUID == Convert.ToInt32(add[i])).Select(p => p).ToList();
                foreach (mtblProductSubCat item in result)
                {
                    info += item.ProductSubCat_Eng + ",";
                }
            }
            for (int i = 0; i < delete.Count - 1; i++)
            {
                var result = list.Where(a => a.ProductCatUID == Convert.ToInt32(delete[i])).Select(p => p).ToList();
                foreach (mtblProductSubCat item in result)
                {
                    info += item.ProductSubCat_Eng + ",";
                }
            }
            info += CheckChange();
            tblUser ent = GetManageFromSession();
            Literal CompanyName = usermeg.FindControl("ltlCompanyName_eng") as Literal;
            tblHistory entlog = new tblHistory();
            entlog.HistoryCatUID = 2;
            entlog.HistoryTypeUID = 26;
            entlog.CustomerUID = customeruid;
            entlog.Cust_MemberUID = 0;
            entlog.ContactPersonUID = 0;
            entlog.History_Detail = ent.User_Name + " {" + CompanyName.Text + "}{BusinessNature}" +info;
            entlog.LastModifyBy = ent.User_Name;
            int tal = tblHistoryBLL.GetInstance().InsertENT(entlog);
        }
        #endregion
    }
}